package com.jcfk.system.utils;

import com.jcfk.system.service.SendWeChatService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
 * 用户关联第三方平台的id
 *
 * @author awei
 * @email 522891237@gqq.com
 * @date 2024-05-14
 */
@Component
public class WechatConfigUtil {
    // 要发送消息的应用的两个字段
    private static Integer agentId;
    private static String secret;
    // 企业id
    private static String corpId;
    // 用于访问redis的密码，没设置就不需要这个字段

    @Value("${wx-cp-config.secret}")
    public void setSecret(String secret) {
        WechatConfigUtil.secret = secret;
    }

    @Value("${wx-cp-config.corpid}")
    public void setCorpId(String corpId) {
        WechatConfigUtil.corpId = corpId;
    }

    @Value("${wx-cp-config.agentid}")
    public void setAgentId(Integer agentId) {
        WechatConfigUtil.agentId = agentId;
    }

    @Autowired
    private SendWeChatService sendWeChatService;
    /**
     * 配置企业微信服务
     *
     * @return
     */
    public static WxCpService getWxCpService() {
        WxCpService wxCpService = new WxCpServiceImpl();
        WxCpDefaultConfigImpl config = new WxCpDefaultConfigImpl();
        config.setAgentId(agentId);
        config.setCorpSecret(secret);
        config.setCorpId(corpId);
        resetTokenAndJsApi(wxCpService, config);

        return wxCpService;
    }

    /**
     * 生成企业微微信类
     *
     * @param wxCpService
     * @param wxCpDefaultConfig
     */
    public static void resetTokenAndJsApi(WxCpService wxCpService, WxCpDefaultConfigImpl wxCpDefaultConfig) {
        wxCpService.setWxCpConfigStorage(wxCpDefaultConfig);
        if (wxCpDefaultConfig.isAccessTokenExpired()) {  // token到期
            try {
                String accessToken = null;
                accessToken = wxCpService.getAccessToken(false);
                wxCpDefaultConfig.setAccessToken(accessToken);
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
        }
    }
}
